#! /bin/sh -e

PREFIX=/usr
BIN=$PREFIX/bin
MAN=$PREFIX/share/man/man1/

die()
{
    echo "$1" >&2
    echo "Installation aborted." >&2
    exit 1
}

echo "This script will uninstall additional material for F# including"
echo "man pages, fsharpc and fsharpi scripts and Gtk# support for F#"
echo "Interactive (root access needed)"
echo ""

# ------------------------------------------------------------------------------
# Utility function that searches specified directories for a specified file
# and if the file is not found, it asks user to provide a directory

RESULT=""

searchpaths()
{
  declare -a DIRS=("${!3}")
  FILE=$2
  DIR=${DIRS[0]}
  for TRYDIR in ${DIRS[@]}
  do
    if [ -f $TRYDIR/$FILE ]
    then
      DIR=$TRYDIR
    fi
  done

  while [ ! -f $DIR/$FILE ]
  do
    echo "File '$FILE' was not found in any of ${DIRS[@]}. Please enter $1 installation directory:"
    read DIR
  done
  RESULT=$DIR
}

# ------------------------------------------------------------------------------
# Locate F# installation directory - this is needed, because we want to 
# add environment variable with it, generate 'fsharpc' and 'fsharpi' and also
# copy load-gtk.fsx to that directory
# ------------------------------------------------------------------------------

PATHS=( $1 /usr/lib/fsharp /usr/lib/shared/fsharp )
searchpaths "F# installation" FSharp.Core.dll PATHS[@]
FSHARPDIR=$RESULT
echo "Successfully found F# installation directory."

# ------------------------------------------------------------------------------
# Check that we have everything we need
# ------------------------------------------------------------------------------

[ $(id -u) -eq 0 ] || die "Please run the script as root."

# ------------------------------------------------------------------------------
# Remove additional assemblies from GAC
# ------------------------------------------------------------------------------

echo "Uninstalling additional F# assemblies to the GAC"
gacutil -u FSharp.Build
gacutil -u FSharp.Compiler
gacutil -u FSharp.Compiler.Interactive.Settings
gacutil -u FSharp.Compiler.Server.Shared

# ------------------------------------------------------------------------------
# Uninstall additional files
# ------------------------------------------------------------------------------

# Uninstall man pages

echo "Uninstalling additional F# commands, scripts and man pages"
rm $MAN\fsharpi.1
rm $MAN\fsharpc.1

# Remove the FSHARP_COMPILER_BIN environment variable
if [[ ! "$OSTYPE" =~ "darwin" ]]; then
  rm /etc/profile.d/fsharp.sh
fi

# Remove  'load-gtk.fsx' script for F# Interactive
rm $FSHARPDIR/load-gtk.fsx

# Remove 'fsharpc' and 'fsharpi' scripts
rm $BIN/fsharpc
rm $BIN/fsharpi
